package ru.spb.osll.myfit.server.parser;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableCell;
import ru.spb.osll.myfit.common.TableStyle;
import ru.spb.osll.myfit.util.CollectionUtils;
import ru.spb.osll.myfit.util.StringUtils;

public class TableCreater {
  //private Logger LOG = Logger.getLogger(PageParser.class);
  public static final String LINE_SEPARATOR = System.getProperty("line.separator");
  public static final String TABLE_SEPARATOR = LINE_SEPARATOR + LINE_SEPARATOR;
  public static final String IMPORT_TABLE = "Import";


  public TableCreater (){
  }
  
  
  
  public Table parseTable(Collection<String> lines) {
    return createTable(TableStyle.UNKNOWN_FIXTURE, tokenizeLines(lines));
  }
  
  public Table createTable(TableStyle style, String... lines) {
    return createTable(style, CollectionUtils.list(lines));
  }
  
  public Table createTable(TableStyle style, Collection<String> lines) {
    Table table = new Table(style);

    Vector<TableCell> tableLine = new Vector<TableCell>();
    for (String line : lines) {
      if (!line.equals(LINE_SEPARATOR) && !line.isEmpty()) {
        tableLine.add(new TableCell(line));
      } else if (tableLine.size() > 0) {
        table.addLine(tableLine);
        tableLine = new Vector<TableCell>();
      }
    }

    if (tableLine.size() > 0) {
      table.addLine(tableLine);
    }

    return table;
  }
  
  private List<String> tokenizeLines(Collection<String> lines) {
    LinkedList<String> splitLines = new LinkedList<String>();
    for (String line : lines) {
      if (line.matches("\\|.*\\|")) {
        splitLines
            .addAll(CollectionUtils.filter(CollectionUtils
                .list(line.split("\\|")),
                StringUtils.FILTER_NOT_EMPTY));
        splitLines.add(LINE_SEPARATOR);
      } else {
        splitLines.add(TABLE_SEPARATOR);
      }
    }

    return splitLines;
  }
}
